<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="套餐名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否热门" prop="isPopular">
        <el-select v-model="queryParams.isPopular" placeholder="请选择" clearable>
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择" clearable>
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:pointsPackage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:pointsPackage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:pointsPackage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:pointsPackage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="pointsPackageList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="packageId" width="80" />
      <el-table-column label="图标" align="center" width="80">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.iconUrl"
            :src="scope.row.iconUrl"
            :preview-src-list="[scope.row.iconUrl]"
            style="width: 50px; height: 50px;"
            fit="contain"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐名称" align="center" prop="packageName" min-width="120" />
      <el-table-column label="积分数量" align="center" prop="pointsAmount" width="100">
        <template slot-scope="scope">
          <el-tag type="warning" size="small">{{ scope.row.pointsAmount }}积分</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" width="150">
        <template slot-scope="scope">
          <div>
            <div style="color: #f56c6c; font-weight: bold; font-size: 16px;">¥{{ scope.row.price }}</div>
            <div v-if="scope.row.discount > 0" style="color: #909399; font-size: 12px; text-decoration: line-through;">
              原价: ¥{{ scope.row.originalPrice }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="折扣" align="center" prop="discount" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.discount > 0" type="danger" size="small">{{ scope.row.discount }}折</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐说明" align="center" prop="packageDescription" min-width="200" show-overflow-tooltip />
      <el-table-column label="热门" align="center" prop="isPopular" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isPopular === 1" type="danger" effect="dark" size="small">🔥 热门</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="启用" align="center" prop="isActive" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActive"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
            v-hasPermi="['system:pointsPackage:edit']"
          />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:pointsPackage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:pointsPackage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改积分套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="套餐名称" prop="packageName">
                  <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="积分数量" prop="pointsAmount">
                  <el-input-number v-model="form.pointsAmount" :min="0" :step="100" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="售价（元）" prop="price">
                  <el-input-number v-model="form.price" :precision="2" :step="0.01" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原价（元）" prop="originalPrice">
                  <el-input-number v-model="form.originalPrice" :precision="2" :step="0.01" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="折扣" prop="discount">
                  <el-input-number v-model="form.discount" :precision="2" :step="0.1" :min="0" :max="10" style="width: 100%" />
                  <span class="form-tip">* 如：8.5表示8.5折，0表示无折扣</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="套餐说明" prop="packageDescription">
                  <el-input 
                    v-model="form.packageDescription" 
                    type="textarea"
                    :rows="4"
                    placeholder="请输入套餐说明"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 显示设置 -->
          <el-tab-pane label="显示设置" name="display">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="套餐图标" prop="iconUrl">
                  <image-upload 
                    v-model="form.iconUrl" 
                    :limit="1"
                    :fileSize="1"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="热门推荐" prop="isPopular">
                  <el-radio-group v-model="form.isPopular">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否启用" prop="isActive">
                  <el-radio-group v-model="form.isActive">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序顺序" prop="sortOrder">
                  <el-input-number v-model="form.sortOrder" :min="0" style="width: 100%" />
                  <span class="form-tip">* 数值越小越靠前</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea"
                    :rows="8"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPointsPackage, getPointsPackage, delPointsPackage, addPointsPackage, updatePointsPackage } from "@/api/system/pointsPackage";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "PointsPackage",
  components: {
    ImageUpload
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      pointsPackageList: [],
      title: "",
      open: false,
      activeTab: 'basic',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        pointsAmount: null,
        price: null,
        discount: null,
        originalPrice: null,
        packageDescription: null,
        isPopular: null,
        isActive: null,
        sortOrder: null,
        iconUrl: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        packageName: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        pointsAmount: [
          { required: true, message: "积分数量不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "售价不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listPointsPackage(this.queryParams).then(response => {
        this.pointsPackageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleStatusChange(row) {
      let text = row.isActive === 1 ? "启用" : "禁用";
      this.$modal.confirm('确认要"' + text + '""' + row.packageName + '"套餐吗？').then(() => {
        return updatePointsPackage(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(() => {
        row.isActive = row.isActive === 0 ? 1 : 0;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        packageId: null,
        packageName: null,
        pointsAmount: 0,
        price: 0,
        discount: 0,
        originalPrice: 0,
        packageDescription: null,
        isPopular: 0,
        isActive: 1,
        sortOrder: 0,
        iconUrl: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.open = true;
      this.title = "添加积分套餐";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const packageId = row.packageId || this.ids
      getPointsPackage(packageId).then(response => {
        this.form = response.data;
        
        // 处理JSON字段
        if (this.form.extraData && typeof this.form.extraData === 'object') {
          this.form.extraData = JSON.stringify(this.form.extraData, null, 2);
        }
        
        this.open = true;
        this.title = "修改积分套餐";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理JSON字段
          if (submitForm.extraData && typeof submitForm.extraData === 'string') {
            try {
              submitForm.extraData = submitForm.extraData.trim() 
                ? JSON.parse(submitForm.extraData) 
                : null;
            } catch (e) {
              this.$modal.msgError("扩展数据JSON格式不正确");
              return;
            }
          }
          
          if (submitForm.packageId != null) {
            updatePointsPackage(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPointsPackage(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const packageIds = row.packageId || this.ids;
      this.$modal.confirm('是否确认删除积分套餐编号为"' + packageIds + '"的数据项？').then(function() {
        return delPointsPackage(packageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/pointsPackage/export', {
        ...this.queryParams
      }, `pointsPackage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
